<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="商机名称" prop="orderId">
        <el-select
          v-model="queryParams.orderId"
          filterable
          clearable
          placeholder="请选择商机"
          size="small"
        >
          <el-option
            v-for="item in orderListAll"
            :key="item.orderId"
            :label="item.orderName"
            :value="item.orderId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="客户" prop="customerId">
        <el-select
          v-model="queryParams.customerId"
          filterable
          clearable
          placeholder="请选择客户"
          size="small"
        >
          <el-option
            v-for="item in customerList"
            :key="item.customerId"
            :label="item.customerName"
            :value="item.customerId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="负责人" prop="userId">
        <el-select
          v-model="queryParams.userId"
          filterable
          clearable
          placeholder="请选择负责人"
          size="small"
        >
          <el-option
            v-for="item in userList"
            :key="item.userId"
            :label="item.userName"
            :value="item.userId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="工单类型" prop="taskType">
        <el-select
          v-model="queryParams.taskType"
          filterable
          clearable
          placeholder="请选择工单类型"
          size="small"
        >
          <el-option
            v-for="dict in dict.type.task_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="负责人" prop="createBy">
        <el-input
          v-model="queryParams.createBy"
          placeholder="请输入负责人"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="研发人员" prop="devUserId">
        <el-select
          v-model="queryParams.devUserId"
          placeholder="请选择"
          multiple
          size="small"
          filterable
        >
          <el-option
            v-for="item in devExpertList"
            :key="item.expertId"
            :label="item.expertName"
            :value="item.expertId"
          >
            <span style="float: left">{{ item.expertName }}</span>
            <span style="float: right; color: #8492a6; font-size: 13px">
              <dict-tag
                :options="dict.type.crm_expert_type"
                :value="item.expertType"
              />
            </span>
          </el-option>
        </el-select>
      </el-form-item> -->

      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['crm:collectPayMoney:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['crm:collectPayMoney:edit']"
          >修改</el-button
        >
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['crm:collectPayMoney:remove']"
          >删除</el-button
        >
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['crm:collectPayMoney:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="taskList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="申请人" align="center" prop="createBy" />
      <el-table-column label="负责人" align="center" prop="userName" />
      <el-table-column label="工单类型" prop="taskType" align="center">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.task_type"
            :value="scope.row.taskType"
          />
        </template>
      </el-table-column>
      <el-table-column label="关联商机" align="center" prop="orderName" />
      <el-table-column label="关联客户" align="center" prop="customerName" />
      <el-table-column label="实施开始时间" align="center" prop="startTime" />
      <el-table-column label="实施结束时间" align="center" prop="endTime" />
      <el-table-column label="实际天数" align="center" prop="actualDay" />
      <el-table-column label="紧急程度" align="center" prop="taskLevel">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.task_level"
            :value="scope.row.taskLevel"
          />
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.task_status"
            :value="scope.row.status"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        fixed="right"
        width="200"
      >
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.status === '0'"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            >修改</el-button
          >
          <el-button
            v-if="scope.row.status === '0'"
            size="mini"
            type="text"
            @click="accomplish(scope.row)"
            >完成</el-button
          >
          <el-button
            v-if="scope.row.status === '1'"
            size="mini"
            type="text"
            @click="handleUpdate(scope.row)"
            >详情</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改工单对话框 -->
    <el-drawer
      ref="drawer"
      :title="title"
      direction="rtl"
      :visible.sync="open"
      size="80%"
      append-to-body
      :wrapperClosable="false"
    >
      <el-card
        class="box-card"
        style="width: 96%; margin-left: 20px; min-height: 90vh"
      >
        <el-row>
          <el-form ref="form" :model="form" :rules="rules" label-width="80px">
            <el-col :span="12">
              <el-form-item label="工单类型" prop="taskType">
                <el-select
                  v-model="form.taskType"
                  filterable
                  placeholder="请选择工单类型"
                  style="width: 100%"
                >
                  <el-option
                    v-for="dict in dict.type.task_type"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="客户名称" prop="customerId">
                <el-select
                  v-model="form.customerId"
                  filterable
                  placeholder="请选择客户名称"
                  style="width: 100%"
                  @change="getCrmOrderAllNoPage(form.customerId)"
                >
                  <el-option
                    v-for="customer in customerList"
                    :key="customer.customerId"
                    :label="customer.customerName"
                    :value="customer.customerId"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="地区" prop="region">
                <el-cascader
                  v-model="form.region"
                  :options="cityTree"
                  :props="cascaderProps"
                  style="width: 100%"
                ></el-cascader>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="商机名称" prop="orderId">
                <el-select
                  v-model="form.orderId"
                  filterable
                  placeholder="请选择商机名称"
                  style="width: 100%"
                >
                  <el-option
                    v-for="order in orderListAll"
                    :key="order.orderId"
                    :label="order.orderName"
                    :value="order.orderId"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="开始时间" prop="startTime">
                <el-date-picker
                  style="width: 100%"
                  clearable
                  v-model="form.startTime"
                  type="date"
                  value-format="yyyy-MM-dd"
                  placeholder="请选择开始时间"
                />
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="结束时间" prop="endTime">
                <el-date-picker
                  style="width: 100%"
                  clearable
                  v-model="form.endTime"
                  type="date"
                  value-format="yyyy-MM-dd"
                  placeholder="请选择结束时间"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="紧急程度" prop="taskLevel">
                <el-select
                  v-model="form.taskLevel"
                  filterable
                  placeholder="请选择紧急程度"
                  style="width: 100%"
                >
                  <el-option
                    v-for="dict in dict.type.task_level"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="实施类型" prop="taskMode">
                <el-select
                  v-model="form.taskMode"
                  filterable
                  placeholder="请选择实施类型"
                  style="width: 100%"
                >
                  <el-option
                    v-for="dict in dict.type.task_mode"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="负责人" prop="userId">
                <el-select
                  v-model="form.userId"
                  filterable
                  placeholder="请选择负责人"
                  style="width: 100%"
                >
                  <el-option
                    v-for="order in userList"
                    :key="order.userId"
                    :label="order.userName"
                    :value="order.userId"
                  />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="应收金额" prop="receivablePayable">
                <el-input
                  v-model.number="form.receivablePayable"
                  placeholder="请输入应收金额"
                  type="number"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="已收金额" prop="receivablePaid">
                <el-input
                  type="number"
                  v-model="form.receivablePaid"
                  placeholder="请输入已收金额款"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="实施价格" prop="taskPrice">
                <el-input
                  type="number"
                  v-model="form.taskPrice"
                  placeholder="请输入实施价格"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12" v-if="isActualDay">
              <el-form-item label="实际天数" prop="actualDay">
                <el-input
                  v-model.number="form.actualDay"
                  placeholder="请输入实际天数"
                  type="number"
                />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="工作日志" prop="remark">
                <el-input
                  v-model="form.remark"
                  type="textarea"
                  placeholder="请输入工作日志"
                />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="工单说明" prop="illustrate">
                <el-input
                  v-model="form.illustrate"
                  type="textarea"
                  placeholder="请输入工单说明"
                />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item>
                <el-button type="primary" v-if="isSubmit" @click="submitForm"
                  >确 定</el-button
                >
                <el-button @click="cancel">取 消</el-button>
              </el-form-item>
            </el-col>
          </el-form>
        </el-row>
      </el-card>
    </el-drawer>

    <!-- 工单完成弹窗 -->
    <el-dialog
      :title="titleAccomplish"
      :visible.sync="openAccomplish"
      width="800px"
      append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-col :span="24">
          <el-form-item label="开始时间" prop="startTime">
            <el-date-picker
              style="width: 100%"
              clearable
              v-model="form.startTime"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="请选择开始时间"
            />
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item label="结束时间" prop="endTime">
            <el-date-picker
              style="width: 100%"
              clearable
              v-model="form.endTime"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="请选择结束时间"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="实际天数" prop="actualDay">
            <el-input
              v-model.number="form.actualDay"
              placeholder="请输入实际天数"
              type="number"
            />
          </el-form-item>
        </el-col>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="subAccomplish">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listTask,
  getTask,
  addTask,
  delTask,
  updateTask,
  accomplishTaskInfo,
} from "@/api/crm/task";
import { getCrmOrderAllNoPage } from "@/api/crm/order";
import { getCityTreeAllByParentId } from "@/api/system/city";
export default {
  name: "task",
  dicts: ["task_type", "task_level", "task_mode", "task_status"],
  props: {
    userList: {
      type: Array,
      default: [],
    },

    customerList: {
      type: Array,
      default: [],
    },
    orderListAll: {
      type: Array,
      default: [],
    },
  },

  data() {
    return {
      cascaderProps: {
        value: "label", // 选项的ID字段
        label: "label", // 选项的显示字段
        children: "children", // 子节点字段
        // checkStrictly: true,
      },
      titleAccomplish: "",

      isSubmit: true,
      cityTree: [],
      orderList: [],
     
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      //付款金额明细
      detailsList: [],
      // 收付款管理表格数据
      taskList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      isActualDay: false,
      openAccomplish: false,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        customerId: null,
        region: null,
        orderId: null,
        taskType: null,
        phone: null,
        address: null,
        startTime: null,
        endTime: null,
        taskLevel: null,
        coPerson: null,
        receivablePayable: null,
        receivablePaid: null,
        taskPrice: null,
        taskMode: null,
        maintenanceId: null,
      },
      // 表单参数
      form: {},

      // 表单校验
      rules: {
        taskType: [
          { required: true, message: "工单类型不能为空", trigger: "change" },
        ],
        userId: [
          { required: true, message: "款项归属人不能为空", trigger: "blur" },
        ],
        orderId: [
          { required: true, message: "商机名称不能为空", trigger: "blur" },
        ],
        customerId: [
          { required: true, message: "客户名称不能为空", trigger: "blur" },
        ],
        taskMode: [
          { required: true, message: "实施类型不能为空", trigger: "change" },
        ],
        // region: [
        //   { required: true, message: "地区不能为空", trigger: "change" },
        // ],
        startTime: [
          {
            required: true,
            message: "实施开始时间不能为空",
            trigger: "change",
          },
        ],
        endTime: [
          {
            required: true,
            message: "实施结束时间不能为空",
            trigger: "change",
          },
        ],
        userId: [
          { required: true, message: "负责人不能为空", trigger: "change" },
        ],
        remark: [
          { required: true, message: "工作日志不能为空", trigger: "change" },
        ],
      },
    };
  },
  created() {
    this.getList();
 
  },

  methods: {
    getCrmOrderAllNoPage(customerId) {
      getCrmOrderAllNoPage({ customerId: customerId }).then((res) => {
        this.orderList = res.data;
        this.form.orderId = "";
      });
    },
    getCityTree() {
      getCityTreeAllByParentId(1).then((response) => {
        this.cityTree = response.data;
        this.cityTree = this.moveJiangxiToFirst(this.cityTree)
      });
    },
    /** 查询工单列表 */
    getList() {
      this.loading = true;
      listTask(this.queryParams).then((response) => {
        this.taskList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
      this.getCityTree();
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.openAccomplish=false
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        customerId: null,
        orderId: null,
        taskType: null,
        phone: null,
        address: null,
        startTime: null,
        endTime: null,
        actualDay: null,
        taskLevel: null,
        coPerson: null,
        receivablePayable: null,
        receivablePaid: null,
        taskPrice: null,
        files: null,
        remark: null,
        status: null,
        region: null,
        illustrate: null,
        signature: null,
        nodeName: null,
        nodeCode: null,
        instanceId: null,
        auditStatus: null,
        flowStatus: null,
        userId: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        taskMode: null,
        maintenanceId: null,
      };
      this.resetForm("form");
      this.isActualDay = false;
      this.isSubmit = true;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.collectPayMoneyId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.isSubmit = true;
      this.title = "新增工单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getTask(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改工单管理";
        this.isActualDay = false;
        if (this.form.status === "1") {
          this.isSubmit = false;
        }
        this.form.region = this.form.region
          ? this.form.region.split(",")
          : null;
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.form.region = this.form.region?.join(",");
          if (this.form.id != null) {
            updateTask(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTask(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },

    subAccomplish() {
      this.$refs["form"].validate((valid) => {
        accomplishTaskInfo(this.form).then((response) => {
          this.$modal.msgSuccess("修改成功");
          this.openAccomplish = false;
          this.getList();
        });
      });
    },
    /** 完成按钮 */
    accomplish(row) {
      this.reset();
      const id = row.id || this.ids;
      getTask(id).then((response) => {
        this.form = response.data;
        this.openAccomplish = true;
        this.titleAccomplish = "完成工单";
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除工单编号为"' + ids + '"的数据项？')
        .then(function () {
          return delTask(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "crm/collectPayMoney/export",
        {
          ...this.queryParams,
        },
        `collectPayMoney_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>

<style scoped>
::v-deep .collectDetailsList .el-table--medium .el-table__cell {
  padding: 0;
}

::v-deep .collectDetailsList .el-input--medium {
  margin: 10px 10px 10px -10px;
}
</style>